package com.bytenebula.asteroid;


import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.UUID;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常状态
     */
    @ExceptionHandler(ByteNebulaException.class)
    public ServiceResult handleByteNebulaExceptionException(ByteNebulaException e, HttpServletRequest request) {
        String traceId = UUID.randomUUID().toString();
        String requestURI = request.getRequestURI();
        log.error("[{}]请求地址: {}: {}", traceId, requestURI, e.getMessage());

        Exception ie = e.getInnerException();
        if (ie != null) {
            log.error("[{}]InnerErrorMessage: {}", traceId, ie.getMessage());
            log.error("[{}]InnerErrorCause: {}", traceId, ie.getCause().toString());
        }
        return ServiceResult.exception(e);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ServiceResult handleException(Exception e, HttpServletRequest request) {
        String traceId = UUID.randomUUID().toString();
        String requestURI = request.getRequestURI();
        log.error("[{}]请求地址: {}, 发生系统异常", traceId, requestURI);
        log.error("[{}]ErrorMessage: {}", traceId, e.getMessage());;
        return ServiceResult.exception(e);
    }

}
